package com.example.dllo.my36kr.ui.fragment;


import android.content.Intent;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.dllo.my36kr.R;
import com.example.dllo.my36kr.model.DrawerBean;
import com.example.dllo.my36kr.model.NewsBannerBean;
import com.example.dllo.my36kr.model.NewsDatasBean;
import com.example.dllo.my36kr.net.SingleVolley;
import com.example.dllo.my36kr.net.VolleyResult;
import com.example.dllo.my36kr.ui.activity.sonactivity.BannerActivity;
import com.example.dllo.my36kr.ui.activity.sonactivity.NewsChildActivity;
import com.example.dllo.my36kr.ui.activity.sonactivity.SearchActivity;
import com.example.dllo.my36kr.ui.activity.sonactivity.VideoActivity;
import com.example.dllo.my36kr.ui.adapter.DrawerAdapter;
import com.example.dllo.my36kr.ui.adapter.NewsAdapter;
import com.example.dllo.my36kr.tools.NewsUrls;
import com.example.dllo.my36kr.ui.custom.MySwipeRefresh;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 新闻界面
 * Created by CPC_272 on 16/8/15.
 */
public class NewsFragment extends AbsBaseFragment implements VolleyResult, View.OnClickListener, AdapterView.OnItemClickListener, Banner.OnBannerClickListener {
    private ImageView showDrew, backDraw,searchTv;
    private TextView title_news;
    private DrawerLayout mDraw;
    private String[] imageUrls;
    private Banner myBanner;
    private ArrayList<DrawerBean> drawerBeen;
    private List<NewsBannerBean.DataBean.PicsBean> picsBeen;
    private ListView ls_News;
    private ListView ls_Draw;
    private String newsReplaceUrl;
    private String url = NewsUrls.ALL_URL;
    private String imageUrl = NewsUrls.News_BannerURL;
    private MySwipeRefresh  mySwipeRefresh;
    private int showItem = 20;

    @Override
    protected int setLayout() {
        return R.layout.fragment_news;
    }

    @Override
    protected void initView() {
        ls_Draw = byView(R.id.ls_drawer);//抽屉的listview
        ls_News = byView(R.id.news_ls);//新闻页的listview
        showDrew = byView(R.id.showDraw);
        backDraw = byView(R.id.back_draw);
        mDraw = byView(R.id.my_draw);
        title_news = byView(R.id.title_tv_news);
        searchTv=byView(R.id.news_search);
        mySwipeRefresh = byView(R.id.sr_lay_news);
    }
    @Override
    protected void initData() {
        refreshData();
        //请求新闻界面ListView的网络数据
        SingleVolley.getInstence(context).startRequest(url, this, 1);
        //请求新闻界面轮布图
        SingleVolley.getInstence(context).startRequest(imageUrl, this, 2);
        showDrew.setOnClickListener(this);
        backDraw.setOnClickListener(this);
        ls_Draw.setOnItemClickListener(this);


        //点击ls_News行布局 并传递给NewsChildActivity
        ls_News.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NewsDatasBean.DataBean.DataBean1 bean1 = (NewsDatasBean.DataBean.DataBean1) parent.getItemAtPosition(position);
                String intentUrl = NewsUrls.ChildUrl + bean1.getFeedId();
                Intent intent = new Intent(context, NewsChildActivity.class);
                intent.putExtra("title", bean1.getTitle());
                Long time = bean1.getPublishTime();
                SimpleDateFormat format = new SimpleDateFormat("HH:mm");
                String formatTime = format.format(new Date(time));
                intent.putExtra("url", intentUrl);
                intent.putExtra("time", formatTime);
                intent.putExtra("writer", bean1.getUser().getName());
                intent.putExtra("tag", bean1.getColumnName());
                intent.putExtra("imageUrl", bean1.getFeatureImg());
                context.startActivity(intent);
            }
        });


        //搜索的点击事件
        searchTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentSearch = new Intent(context, SearchActivity.class);
                context.startActivity(intentSearch);
            }
        });

        addDrawLs();
    }
       //下拉刷新 和上来加载的方法
    private void refreshData() {
        mySwipeRefresh.setOnLoadListener(new MySwipeRefresh.OnLoadListener() {
            @Override
            public void onLoad() {
                //要做的事情，这里再次调用此Runnable对象，以实现每两秒实现一次的定时器操作
                mySwipeRefresh.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showItem += 2;
                        refreshVolley();
                        // 更新完后调用该方法结束刷新
                        mySwipeRefresh.setLoading(false);
                    }
                }, 2000);
            }
        });
        mySwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mySwipeRefresh.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showItem = 20;
                        refreshVolley();
                        //在onCreate里或onCreateView里调用setRefreshing，
                        // 这个时候关键变量mOriginalOffsetTop并没有获取正确的值。
                        // 下拉效果动画过程中没有显示到正确的坐标，我们看看这个值是什么时候获取的，
                        mySwipeRefresh.setRefreshing(false);
                    }
                }, 2000);
            }
        });
    }

    //把抽屉的listView加载数据
    public void addDrawLs() {
        drawerBeen = new ArrayList<>();
        drawerBeen.add(new DrawerBean(R.mipmap.drawer_black, "全部"));
        drawerBeen.add(new DrawerBean(R.mipmap.drawer_green, "早期项目"));
        drawerBeen.add(new DrawerBean(R.mipmap.drawer_qian_green, "B轮后"));
        drawerBeen.add(new DrawerBean(R.mipmap.drawer_qianlan, "大公司"));
        drawerBeen.add(new DrawerBean(R.mipmap.drawer_blue, "资本"));
        drawerBeen.add(new DrawerBean(R.mipmap.drawer_red, "深度"));
        drawerBeen.add(new DrawerBean(R.mipmap.drawer_yellow, "研究"));
        drawerBeen.add(new DrawerBean(R.mipmap.drawer_pink, "氪TV"));
        DrawerAdapter drawerAdapter = new DrawerAdapter(getContext());
        drawerAdapter.setData(drawerBeen);
        ls_Draw.setAdapter(drawerAdapter);
    }

    @Override
    public void success(String str, int type) {
        Gson gson = new Gson();
        switch (type) {
            case 1://解析新闻的url
                NewsDatasBean newsDatasBean = gson.fromJson(str, NewsDatasBean.class);
                NewsAdapter newsAdapter = new NewsAdapter(getContext());
                newsAdapter.setData(newsDatasBean);
                ls_News.setAdapter(newsAdapter);
                break;
            case 2://解析轮播图的url
                NewsBannerBean banner = gson.fromJson(str, NewsBannerBean.class);
                picsBeen = banner.getData().getPics();
                imageUrls = new String[picsBeen.size()];
                for (int i = 0; i < picsBeen.size(); i++) {
                    imageUrls[i] = picsBeen.get(i).getImgUrl();
                }
                showBanner();
                break;
                //解析抽屉
               case 3:
                NewsDatasBean newsDatasBean1= gson.fromJson(str,NewsDatasBean.class);
                NewsAdapter newsAdapter1=new NewsAdapter(getContext());
                newsAdapter1.setData(newsDatasBean1);
                ls_News.setAdapter(newsAdapter1);
                 //解析刷新加载
                 case 4:
                 NewsDatasBean newsDatasBean2 =gson.fromJson(str,NewsDatasBean.class);
                     NewsAdapter newsAdapter2 = new NewsAdapter(getContext());
                     newsAdapter2.setData(newsDatasBean2);
                     ls_News.setAdapter(newsAdapter2);
                 break;
        }
    }

    @Override
    public void success(String str) {

    }

    @Override
    public void failure() {
    }
         //Banner的方法(轮播图)
    public void showBanner() {
        View views = LayoutInflater.from(context).inflate(R.layout.news_banner, null);
        myBanner = (Banner) views.findViewById(R.id.news_Banner);
        //设置小圆点
        myBanner.setBannerStyle(Banner.CIRCLE_INDICATOR);
        //设置位置
        myBanner.setIndicatorGravity(Banner.CENTER);
        //设置延迟时间
        myBanner.setDelayTime(2000);
        myBanner.setImages(imageUrls);
        myBanner.setOnBannerClickListener(this);
        //添加头视图
        ls_News.addHeaderView(views);
    }


    //抽屉的点击事件打开关闭
    @Override
    public void onClick(View v) {
        switch (v.getId()) {//打开抽屉的方法
            case R.id.showDraw:
                mDraw.openDrawer(Gravity.LEFT);
                break;
            case R.id.back_draw://关闭抽屉的方法
                mDraw.closeDrawer(Gravity.LEFT);
                break;
        }
    }
    //抽屉的item的点击事件 点击每个item跳到解析新的URL
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //给新闻标题  根据抽屉的lisview Item的给标题设置新的文字
        DrawerBean drawerBean = (DrawerBean) parent.getItemAtPosition(position);
        String draw_tv = drawerBean.getTv_draw();
        switch (position) {
            case 0://根据位置替换URL +mDraw.closeDrawer(Gravity.LEFT),是每次点击抽屉也就关了
                myBanner.setVisibility(myBanner.VISIBLE);//显示listView的头视图(也是就轮播图的布局)
                newsReplaceUrl = NewsUrls.ALL_URL;
                title_news.setText(draw_tv);
                replaceNewsDatas();
                mDraw.closeDrawer(Gravity.LEFT);
                break;
            case 1:
                myBanner.setVisibility(myBanner.GONE);//隐藏listview的头视图(也是就轮播图的布局)
                newsReplaceUrl = NewsUrls.EARLY_URL;
                title_news.setText(draw_tv);
                replaceNewsDatas();
                mDraw.closeDrawer(Gravity.LEFT);
                //跳到另一个fragment 这个fragment里面没有轮播图的头布局
//                FragmentManager fragmentManager=getFragmentManager();
//                FragmentTransaction transaction=fragmentManager.beginTransaction();
//                NewsDrawerFragment newsDrawerFragment=new NewsDrawerFragment();
//                Bundle bundle=new Bundle();
//                bundle.putString("type",NewsUrls.EARLY_URL);
//                newsDrawerFragment.setArguments(bundle);
//                transaction.add(R.id.my_draw,newsDrawerFragment).addToBackStack(null).commit();
//                mDraw.closeDrawer(Gravity.LEFT);
                break;
            case 2:
                myBanner.setVisibility(myBanner.GONE);//隐藏listview的头视图(也是就轮播图的布局)
                newsReplaceUrl = NewsUrls.AFTER_B_URL;
                title_news.setText(draw_tv);
                replaceNewsDatas();
                mDraw.closeDrawer(Gravity.LEFT);
                break;
            case 3:
                myBanner.setVisibility(myBanner.GONE);//隐藏listview的头视图(也是就轮播图的布局)
                newsReplaceUrl = NewsUrls.BIG_URL;
                title_news.setText(draw_tv);
                replaceNewsDatas();
                mDraw.closeDrawer(Gravity.LEFT);
                break;
            case 4:
                myBanner.setVisibility(myBanner.GONE);//隐藏listview的头视图(也是就轮播图的布局)
                newsReplaceUrl = NewsUrls.CAPITAL_URL;
                title_news.setText(draw_tv);
                replaceNewsDatas();
                mDraw.closeDrawer(Gravity.LEFT);
                break;
            case 5:
                myBanner.setVisibility(myBanner.GONE);//隐藏listview的头视图(也是就轮播图的布局)
                newsReplaceUrl = NewsUrls.DEEP_URL;
                title_news.setText(draw_tv);
                replaceNewsDatas();
                mDraw.closeDrawer(Gravity.LEFT);
                break;
            case 6:
                myBanner.setVisibility(myBanner.GONE);//隐藏listview的头视图(也是就轮播图的布局)
                newsReplaceUrl = NewsUrls.STUDY_URL;
                title_news.setText(draw_tv);
                replaceNewsDatas();
                mDraw.closeDrawer(Gravity.LEFT);
                break;
            case 7:
                Intent  intent = new Intent(context, VideoActivity.class);
                context.startActivity(intent);
                break;
        }
    }
       //抽屉解析
       public void replaceNewsDatas() {
         SingleVolley.getInstence(getContext()).startRequest(newsReplaceUrl, this, 3);
    }
    @Override
    public void OnBannerClick(View view, int position) {
        //传网址
        //String bannerUrl = picsBeen.get(position ).getLocation();//不-1 轮播图最后一张会崩
        String bannerUrl = picsBeen.get(position - 1).getLocation();
        Intent bannerIntent = new Intent(context, BannerActivity.class);
        bannerIntent.putExtra("bannerUrl", bannerUrl);
        context.startActivity(bannerIntent);
    }
    public void refreshVolley() {
        SingleVolley.getInstence(context).startRequest(NewsUrls.TOP_NEWS_URL + showItem + NewsUrls.BOTTOM_NEWS_URL, this, 4);
    }
}

